package com.ligong.gptai.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.ligong.gptai.service.OpenAIService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

/**
 * @author lwlianghehe@gmail.com
 * @date 2025/9/11
 */
@RestController
@RequestMapping("/api/openai")
public class OpenAiController {
    @Autowired
    private OpenAIService openAIService;

    @PostMapping("/chat/text")
    public Map sendText(String model, String message) throws JsonProcessingException {
        return openAIService.sendText(model, message);
    }

    @PostMapping("/chat/text/stream")
    public SseEmitter sendTextStream(String model, String message) throws JsonProcessingException {
        // 0 表示不超时；生产可根据需要设置超时并做心跳保活
        SseEmitter emitter = new SseEmitter(0L);
        // 将阻塞式上游读取放入异步，避免占用 Servlet 线程
        CompletableFuture.runAsync(() -> {
            try {
                // 从 OpenAI 上游逐片读取并转发到浏览器（事件名统一为 delta）
                openAIService.sendText(model, message, true, delta -> {
                    try {
                        emitter.send(SseEmitter.event().name("delta").data(delta));
                    } catch (IOException e) {
                        emitter.completeWithError(e);
                    }
                });
                // 上游完成后通知前端结束
                emitter.send(SseEmitter.event().name("done").data("[DONE]"));
                emitter.complete();
            } catch (Exception ex) {
                emitter.completeWithError(ex);
            }
        });
        return emitter;
    }

    @PostMapping("create/image")
    public Map createImage(@RequestBody Map<String, Object> params) throws JsonProcessingException {
        String model = (String) params.get("model");
        String prompt = (String) params.get("prompt");
        String size = (String) params.get("size");

        return openAIService.createImage(model, prompt, 1, size);
    }
}
